#include "DatabaseConn.h"
#include "dbcFactory.h"

LIBDBC_BEGIN_NAMESPACE


DatabaseConn::DatabaseConn(string dbms, string host, string database)
{
  _useCredentials = false;
  _host = host;
  _database = database;
  _started = 0;

  // create a datacon object depending on dbms
  _datacon = dbcFactory::createDatabaseInterface( dbms.c_str() );
}

DatabaseConn::DatabaseConn(string dbms, string host, string database, string user, string pwd)
{
  _useCredentials = true;
  _host = host;
  _database = database;
  _user = user;
  _pwd = pwd;
  _started = 0;
  
  // create a datacon object depending on dbms
  _datacon = dbcFactory::createDatabaseInterface( dbms.c_str() );
}



DatabaseConn::~DatabaseConn(void)
{
  if ( _datacon )
  {
    dbcFactory::freeDatabaseInterface( &_datacon );
  }
}

bool DatabaseConn::queryingStart()
{
  bool bConnect = _datacon->isConnected();

  if ( !bConnect )
  {
    bConnect = _useCredentials?
                  _datacon->connect( _host.c_str(), _database.c_str(), _user.c_str(), _pwd.c_str() ) :
                    _datacon->connect( _host.c_str(), _database.c_str(), NULL, NULL, 0);
  }
  _started++;

  return bConnect;
}

/*
cppdbc::IResultSet* DatabaseConn::query(string query)
{
  return _datacon->execQuery( query.c_str() );
}
*/


bool DatabaseConn::queryingEnd()
{
  if ( (--_started) == 0)
  {
    _datacon->close();
  }

  return true;
}

IDatabase* DatabaseConn::getConnectedDatabaseHandler()
{
  queryingStart();
  return _datacon;
}

void DatabaseConn::markConnectionUnused()
{
  queryingEnd();
}


LIBDBC_END_NAMESPACE
